package com.jpragma.blazeds.utils;

import java.io.InputStream;
import java.util.Stack;

import flex.messaging.config.ConfigurationException;
import flex.messaging.config.ConfigurationFileResolver;

public class ClasspathConfigurationFileResolver implements ConfigurationFileResolver {
	private Stack configurationPathStack = new Stack();

	private ClassLoader getDefaultClassLoader() {
		return Thread.currentThread().getContextClassLoader();
	}

	public InputStream getConfigurationFile(String path) {
		InputStream is = getDefaultClassLoader().getResourceAsStream(path);
		if (is != null) {
			pushConfigurationFile(path);
			return is;
		} else {
			ConfigurationException e = new ConfigurationException();
			e.setMessage(11108, new Object[] { path });
			throw e;
		}
	}

	public InputStream getIncludedFile(String src) {
		String path = configurationPathStack.peek() + "/" + src;
		InputStream is = getDefaultClassLoader().getResourceAsStream(path);
		if (is != null) {
			pushConfigurationFile(path);
			return is;
		} else {
			ConfigurationException e = new ConfigurationException();
			e.setMessage(11107, new Object[] { path });
			throw e;
		}
	}

	public void popIncludedFile() {
		configurationPathStack.pop();
	}

	private void pushConfigurationFile(String path) {
		String topLevelPath = path.substring(0, path.lastIndexOf("/"));
		configurationPathStack.push(topLevelPath);
	}
}
